import { defineStore } from 'pinia';
import { MessageReceiveOptType } from '@openim/client-sdk';

import { IMSDK, IMMethods } from '@/utils/im';
// import { getBusinessInfo } from '@/services/user';
import { clearIMProfile } from '@/utils/storage';
import store from './index';

// import useContactStore from './contact';
import useConversationStore from './conversation';

import type { BusinessUserInfo } from '@/types/index';
import type { FriendUserItem } from '@openim/client-sdk';

// import { feedbackToast, filterEmptyValue } from '@/utils/common';

export type FullSelfInfo = FriendUserItem & {
  globalRecvMsgOpt?: MessageReceiveOptType;
} & BusinessUserInfo;

interface StateType {
  selfInfo: BusinessUserInfo;
  isSyncing: boolean;
  reinstall: boolean;
  progress: number;
}

const useStore = defineStore('user', {
  state: (): StateType => ({
    selfInfo: {} as BusinessUserInfo,
    isSyncing: false,
    reinstall: false,
    progress: 0,
  }),
  getters: {
    storeSelfInfo: state => state.selfInfo,
    storeIsSyncing: state => state.isSyncing,
    storeReinstall: state => state.reinstall,
    storeProgress: state => state.progress,
  },
  actions: {
    async getSelfInfoFromReq() {
      try {
        const { data } = await IMSDK.asyncApi(IMMethods.GetSelfUserInfo, IMSDK.uuid());
        // const res = await getBusinessInfo(data.userID);
        // const businessData = res.data.users[0] ?? {};
        // filterEmptyValue(businessData as any);
        this.selfInfo = {
          ...data,
          // ...businessData,
        };
      } catch (error) {
        console.log('test-zcs', error);

        // feedbackToast({ error, message: i18nt('messageTip.getUserInfoFailed') });
        this.userLogout();
      }
    },
    updateSelfInfo(info: Partial<BusinessUserInfo>) {
      this.selfInfo = { ...this.selfInfo, ...info };
    },
    async userLogout(force?: boolean) {
      const useConversatione = useConversationStore();
      // const useContact = useContactStore();

      if (!force) await IMSDK.asyncApi(IMMethods.Logout, IMSDK.uuid());
      clearIMProfile();
      this.selfInfo = {} as BusinessUserInfo;
      useConversatione.clearConversationStore();
      // useContact.clearContactStore();
    },
  },
});

export default function useUserStore() {
  return useStore(store);
}
